package com.huizhonglm.diap.ui.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.DiapApplication;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.API;
import com.huizhonglm.diap.api.HttpCallback;
import com.huizhonglm.diap.api.model.user.MyWalletResponse;
import com.huizhonglm.diap.api.model.user.OrderInfo;
import com.huizhonglm.diap.api.model.wallet.AliOrderResponse;
import com.huizhonglm.diap.api.model.wallet.CashConfirmParams;
import com.huizhonglm.diap.api.model.wallet.PaymentParams;
import com.huizhonglm.diap.api.model.wallet.WxOrderParams;
import com.huizhonglm.diap.api.model.wallet.WxOrderResponse;
import com.huizhonglm.diap.core.config.Constants;
import com.huizhonglm.diap.core.storage.pref.Preferences;
import com.huizhonglm.diap.core.utils.DialogUtil;
import com.huizhonglm.diap.core.utils.LogUtil;
import com.huizhonglm.diap.core.utils.RSAUtil;
import com.huizhonglm.diap.core.utils.TPWDUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.model.AliPayResult;
import com.huizhonglm.diap.presenters.wallet.PaymentPresenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.user.FinishUserInfoActivity;
import com.huizhonglm.diap.ui.wallet.iView.PaymentIView;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLConnection;

/**
 * 确认支付页面
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2015-07-07 09:14
 */
public class PaymentActivity extends BaseActivity implements PaymentIView, View.OnClickListener {
    private final int MSG_WHAT_PAY_AL = 1;
    private final int MSG_WHAT_PAY_UP = 3;

    private Button cashConfirmBtn;
    private TextView cashPayTxt;

    private PaymentPresenter mPresenter;
    private PaymentHandler mHandler;

    private MyWalletResponse wallet;
    private OrderInfo order;

    private TPWDUtil tpwdUtil;

    /**
     * 银联支付
     */
    private String upPayMode;// 参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
    private final String upPayURL = "http://101.231.204.84:8091/sim/getacptn";

    /**
     * 微信支付
     */
    private IWXAPI wxAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment);
        setBackEvent(this, null);
        wallet = (MyWalletResponse) getIntent().getSerializableExtra("wallet");
        order = (OrderInfo) getIntent().getSerializableExtra("order");
        wxAPI = WXAPIFactory.createWXAPI(this, Constants.WECHAT_APPID,true);
        mPresenter = new PaymentPresenter(this);
        mHandler = new PaymentHandler(PaymentActivity.this);
        assignViews();
    }

    @Override
    protected void assignViews() {
        TextView totalPrice = (TextView) findViewById(R.id.total_price_txt);
        TextView walletAmount = (TextView) findViewById(R.id.wallet_amount_txt);
        Button quickPayBtn = (Button) findViewById(R.id.quick_payment_btn);
        cashConfirmBtn = (Button) findViewById(R.id.cash_confirm_btn);
        View wxPay = findViewById(R.id.wx_payment_txt);
        View zfbPay = findViewById(R.id.zfb_payment_txt);
        View upPay = findViewById(R.id.up_payment_txt);
        cashPayTxt = (TextView) findViewById(R.id.cash_payment_txt);

        totalPrice.setText("￥ " + order.getTotalPrice() + "元");
        walletAmount.setText("平台账户资金：￥" + wallet.getBalance());
        if (wallet.getBalance() != null && wallet.getBalance() < order.getTotalPrice()) {
            quickPayBtn.setEnabled(false);
            quickPayBtn.setText("平台账户资金不足，请选择其他支付方式！！！");
        } else {
            quickPayBtn.setEnabled(true);
            quickPayBtn.setText("立即支付");
        }
        quickPayBtn.setOnClickListener(this);
        cashConfirmBtn.setOnClickListener(this);
        wxPay.setOnClickListener(this);
        zfbPay.setOnClickListener(this);
        upPay.setOnClickListener(this);
        cashPayTxt.setOnClickListener(this);

        // TODO: 暂时屏蔽掉银联支付按钮
        upPay.setVisibility(View.GONE);

        if(order.getShopId().equalsIgnoreCase("8aae324f5a5911c9015ac62334350020")){
            cashPayTxt.setVisibility(View.GONE);
        }
        // 根据微信版本判断是否可以使用微信支付
        if (wxAPI.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT) {
            wxPay.setVisibility(View.VISIBLE);
        } else {
            wxPay.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Preferences.getInstance().getInt("wxpayEC", 3) <= 0) {
            Preferences.getInstance().edit().putInt("wxpayEC", 3).apply();
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.quick_payment_btn:
//                quickPayment();
                showProgressBar();
                mPresenter.checkSetTPWD();
                break;
            case R.id.cash_confirm_btn:
                cashConfirm();
                break;
            case R.id.wx_payment_txt:
                showProgressBar();
                getWxOrderInfo();
                break;
            case R.id.zfb_payment_txt:
                mPresenter.getAliOrderInfo(order.getOrderId());
                break;
            case R.id.up_payment_txt:
                upPay();
                break;
            case R.id.cash_payment_txt:
                if (cashConfirmBtn.getVisibility() == View.VISIBLE) {
                    cashConfirmBtn.setVisibility(View.GONE);
                    cashPayTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_cash_payment, 0, R.drawable.ic_arrow_right, 0);
                } else {
                    cashConfirmBtn.setVisibility(View.VISIBLE);
                    cashPayTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_cash_payment, 0, R.drawable.ic_arrow_down, 0);
                }
                break;
        }
    }

    @Override
    public void getAliOrderSuccess(AliOrderResponse resp) {
        String orderInfo = resp.getOrderInfo();
        if (EmptyUtil.isEmpty(orderInfo)) {
            ToastUtil.makeTextShort("生成订单失败，请稍后重试");
        } else {
            alPay(orderInfo);
        }
    }

    @Override
    public void getAliOrderFailure() {
        ToastUtil.makeTextShort("生成订单失败，请稍后重试");
    }

    @Override
    public void onQuickPaymentSuccess() {
        hideProgressBar();
        // 跳转到支付成功页面
        startActivity(new Intent(this, PaymentSuccessActivity.class));
        finish();
    }

    @Override
    public void onQuickPaymentFailure(String msg) {
        hideProgressBar();
        DialogUtil.showConfirmDialog(this, "支付失败", msg, null);
    }

    @Override
    public void onCashConfirmSuccess() {
        hideProgressBar();
        // 跳转到支付成功页面
        startActivity(new Intent(this, PaymentSuccessActivity.class));
        finish();
    }

    @Override
    public void onCashConfirmFailure(String msg) {
        hideProgressBar();
        DialogUtil.showConfirmDialog(this, "确认失败", msg, null);
    }

    @Override
    public void onCheckSetTPWD(boolean isSetted){
        if (isSetted) {
            hideProgressBar();
            showTPWDInputDialog();
        } else {
            mPresenter.checkSetUserInfo();
        }
    }

    @Override
    public void onCheckTPWD(boolean isSuccess){
        hideProgressBar();
        if (isSuccess) {
            quickPayment();
        } else {
            ToastUtil.makeTextShort("密码错误");
        }
    }

    @Override
    public void onCheckSetUserInfo(boolean isSetted){
        hideProgressBar();
        if (isSetted) {
            // 设置交易密码
            startActivity(new Intent(this, TPWDSettingActivity.class));
        } else {
            // 完善资料
            startActivity(new Intent(this, FinishUserInfoActivity.class));
        }
    }

    private void showTPWDInputDialog() {
        if (tpwdUtil == null) {
            tpwdUtil = new TPWDUtil(PaymentActivity.this, new TPWDUtil.OnInputCompleteListener() {
                @Override
                public void onInputCompleted(String tpwd) {
                    showProgressBar();
                    mPresenter.checkTPWD(tpwd);
                }
            });
        }
        tpwdUtil.showDialog();
    }

    /**
     * 快捷支付
     */
    private void quickPayment(){
        showProgressBar();
        PaymentParams params = new PaymentParams();
        params.orderId = order.getOrderId();
        params.payType = "5";
        mPresenter.onQuickPayment(params);
    }

    /**
     * 请商家确认
     */
    private void cashConfirm(){
        showProgressBar();
        CashConfirmParams params = new CashConfirmParams();
        params.orderId = order.getOrderId();
        params.shopId = order.getShopId();
        params.userId = UserUtil.getUserId();
        mPresenter.cashConfirm(params);
    }

    private void alPay(final String orderInfo) {
        LogUtil.print("aliPayResult--->orderInfo=" + orderInfo);
        try {
            // 完整的符合支付宝参数规范的订单信息
            Runnable alPayRun = new Runnable() {

                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(PaymentActivity.this);
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(orderInfo, true);
                    Message msg = new Message();
                    msg.what = MSG_WHAT_PAY_AL;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            new Thread(alPayRun).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void upPay(){
        if (DiapApplication.isDebug) {
            upPayMode = "01";
        } else {
            upPayMode = "00";
        }
        /**
         * 【银联支付】步骤1：从网络开始,获取交易流水号即TN
         */
        Runnable upPayRun = new Runnable() {
            @Override
            public void run() {
                String tn = null;
                InputStream is;
                try {
                    URL myURL = new URL(upPayURL);
                    URLConnection ucon = myURL.openConnection();
                    ucon.setConnectTimeout(120000);
                    is = ucon.getInputStream();
                    int i;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    while ((i = is.read()) != -1) {
                        baos.write(i);
                    }
                    tn = baos.toString();
                    is.close();
                    baos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Message msg = new Message();
                msg.what = MSG_WHAT_PAY_UP;
                msg.obj = tn;
                mHandler.sendMessage(msg);
            }
        };
        new Thread(upPayRun).start();
    }

    private void handleMessage(Message msg) {
        hideProgressBar();
        switch (msg.what) {
            case MSG_WHAT_PAY_AL:
                AliPayResult payResult = new AliPayResult((String) msg.obj);
                // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                String memo = payResult.getMemo();// 提示信息【可空，保留参数，一般无内容】
                String result = payResult.getResult();// 本次操作返回的结果数据【不可空】
                String resultStatus = payResult.getResultStatus();// 状态代码【不可空】
                LogUtil.print("aliPayResult--->resultStatus=" + resultStatus);
                LogUtil.print("aliPayResult--->result=" + result);
                LogUtil.print("aliPayResult--->memo=" + memo);
                // 判断resultStatus为“9000”则代表支付成功
                switch (resultStatus) {
                    case "9000":// 订单支付成功
                    case "8000":// 正在处理中【支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）】
                        ToastUtil.makeTextShort("支付成功");
                        // 跳转到支付成功页面
                        startActivity(new Intent(this, PaymentSuccessActivity.class));
                        finish();
                        break;
                    case "6001":// 用户中途取消
                        ToastUtil.makeTextShort("取消支付");
                        break;
                    default: // 订单支付失败【4000】、网络连接出错【6002】
                        ToastUtil.makeTextShort("支付失败");
                        break;
                }
                break;
            case MSG_WHAT_PAY_UP:
                if (msg.obj == null || ((String) msg.obj).length() == 0) {
                    showTipDialog("错误提示", "网络连接失败,请重试!");
                } else {
                    LogUtil.print("UPPAY -- tn::" + msg.obj);
                    /**
                     * 【银联支付】步骤2：通过银联工具类启动支付插件
                     */
                    UPPayAssistEx.startPay(PaymentActivity.this, null, null, (String) msg.obj, upPayMode);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 【银联支付】步骤3：处理银联手机支付控件返回的支付结果
         */
        if (data == null)
            return;
        // 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
        String str = data.getExtras().getString("pay_result");
        LogUtil.print("unionPay -- result=" + data.getExtras().toString());
        if ("success".equalsIgnoreCase(str)) {
            // 支付成功后，extra中如果存在result_data，取出校验
            // result_data结构见c）result_data参数说明
            if (data.hasExtra("result_data")) {
                String result = data.getExtras().getString("result_data");
                try {
                    JSONObject resultJson = new JSONObject(result);
                    String sign = resultJson.getString("sign");
                    String dataOrg = resultJson.getString("data");
                    // 验签证书同后台验签证书
                    // 此处的verify，商户需送去商户后台做验签
                    boolean ret = RSAUtil.verify(dataOrg, sign, upPayMode);
                    if (ret) {
                        // 验证通过后，显示支付结果
                        // TODO：实现银联支付成功后续操作【暂时跳转到支付成功页面】
                        startActivity(new Intent(this, PaymentSuccessActivity.class));
                        finish();
                    } else {
                        // 验证不通过后的处理
                        // 建议通过商户后台查询支付结果
                        ToastUtil.makeTextShort("支付失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                // 未收到签名信息
                // 建议通过商户后台查询支付结果
                showTipDialog("未收到返回结果","请联系商家查询支付结果");
            }
        } else if ("fail".equalsIgnoreCase(str)) {
            ToastUtil.makeTextShort("支付失败");
        } else if ("cancel".equalsIgnoreCase(str)) {
            ToastUtil.makeTextShort("支付取消");
        }
    }

    private void showTipDialog(String title, String msg){
        DialogUtil.showConfirmDialog(this, title, msg, null);
    }


    public static class PaymentHandler extends Handler {
        WeakReference<PaymentActivity> wrf;

        public PaymentHandler(PaymentActivity activity) {
            this.wrf = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            PaymentActivity activity = wrf.get();
            if (activity != null) {
                activity.handleMessage(msg);
            }
        }
    }

    public void getWxOrderInfo() {
        WxOrderParams params = new WxOrderParams();
        params.orderId = order.getOrderId();
        Constants.WECHAT_ORDER_ID=order.getOrderId();
        API.http().post("getWxOrderInfo", params, new HttpCallback() {
            @Override
            public void onSuccess(String result) {
                LogUtil.print("getWxOrderInfo -- resp=" + result);
                hideProgressBar();
                if (!EmptyUtil.isEmpty(result)) {
                    WxOrderResponse resp = JSON.parseObject(result, WxOrderResponse.class);
                    if (resp != null) {
                        PayReq req = new PayReq();
                        req.appId			= resp.getAppid()+"";
                        req.partnerId		= resp.getPartnerid()+"";
                        req.prepayId		= resp.getPrepayid()+"";
                        req.packageValue	= "Sign=WXPay";
                        req.nonceStr		= resp.getNoncestr()+"";
                        req.timeStamp		= resp.getTimestamp() + "";
                        req.sign			= resp.getSign()+"";
                        wxAPI.registerApp(Constants.WECHAT_APPID);
                        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                        wxAPI.sendReq(req);
                    } else {
                        ToastUtil.makeTextShort("微信支付失败");
                    }
                } else {
                    ToastUtil.makeTextShort("微信支付失败");
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                hideProgressBar();
                ToastUtil.makeTextShort("微信支付失败");
            }
        });
    }
}
